<?php

namespace app\admin\controller\financing;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Env;

/**
 * 会员收费
 *
 * @icon fa fa-user
 */
class Cost extends Backend
{


    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $models = null;
    protected $categorylist = [];
    private $redis;

    public function _initialize()
    {
        parent::_initialize();
        //$this->model = new \app\admin\model\Registration;
        $this->model = new \app\admin\model\Cost;
        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(["users"=>['id','name'],"medic"=>['id','name'],"info"=>['id','name']])
                //->with(["users"=>['id','nickname','phone']])
                ->with([
                    'users' => function ($query) {
                        $query->withField('id,nickname,phone');
                    }
                ])
                ->where($where)
                ->order('id', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    //1代表转账，2代表现金，3代表pos机，4代表支付宝，5代表微信
                    switch ($v->pay){
                        case 1:
                            $list->items()[$k]->pay = '转账';
                            break;
                        case 2:
                            $list->items()[$k]->pay = '现金';
                            break;
                        case 3:
                            $list->items()[$k]->pay = 'pos机';
                            break;
                        case 4:
                            $list->items()[$k]->pay = '支付宝';
                            break;
                        case 5:
                            $list->items()[$k]->pay = '微信';
                            break;
                        default:
                            $list->items()[$k]->pay = '无';
                            break;
                    }
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 查询操作
     *
     */
    public function for(){
        $arr = request()->param();

        $data = Db::table('fa_users')
            ->where('id',$arr['id'])
            ->find();

        if (empty($data)){
            $this->error('用户数据为空');
        }else{

            if ($data['pid'] != 0){
                $this->error('该账户不是主账户');
            }

            $this->success('成功','',$data['nickname']);
        }

    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                if (empty($params['user_id'])){
                    $this->error(__('客户id不能为空'));
                }

                if (empty($params['money'])){
                    $this->error(__('收款金额不能为空或0'));
                }

                if (!is_numeric($params['money'])){
                    $this->error(__('金额只能为数字类型'));
                }

                $user_arr = Db::table('fa_users')
                    ->where('id',$params['user_id'])
                    ->find();

                if ($user_arr['pid'] != 0){
                    $this->error('该账户不是主账户');
                }


                $params['admin_id'] = $this->auth->id;
                $params['admin_name'] = $this->auth->nickname;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }


                    $info_count = Db::table('fa_info')
                        ->where('user_id',$params['user_id'])
                        ->count();

                    $counts = 0;
                    if ($user_arr['level'] == 1){

                        $vip_time = date('Y-m-d',strtotime(" +365 day"));

                        if ($params['cost_way'] == 1){
                            $vip_arr = Db::table('fa_vip_level')
                                ->where('id','in',[2,3])
                                ->select();
                            $level = 1;
                            foreach ($vip_arr as $k=>$v){
                                if ($params['money'] >= $v['price']){
                                    $level = $v['id'];
                                }else{
                                    if($v['id'] == 2){
                                        $this->error(__('收款金额低于会员费'));
                                    }
                                }

                            }

                            if ($level == 3){
                                $counts = 8;

                                if ($info_count > 8){
                                    $this->error(__('该账号下就诊人数量大于8,请删除就诊人后再操作'));
                                }
                            }

                            if ($info_count > 1){
                                $this->error(__('该账号下就诊人数量大于1,请删除就诊人后再操作'));
                            }


                        }elseif ($params['cost_way'] == 2){
                            $this->error(__('请先充值成为会员'));
                        }elseif ($params['cost_way'] == 3){
                            $this->error(__('请先充值成为家庭会员'));
                        }

                    }elseif ($user_arr['level'] == 2){

                        if ($params['cost_way'] == 1){
                            $vip_time = date('Y-m-d',strtotime(" +365 day"));
                            $vip_arr = Db::table('fa_vip_level')
                                ->where('id',3)
                                ->find();
                            if ($params['money'] >= $vip_arr['price']){
                                $level = $vip_arr['id'];
                            }else{
                                $this->error(__('收款金额低于会员费'));
                            }

                            if ($level == 3){
                                $counts = 8;
                            }

                        }elseif ($params['cost_way'] == 2){
                            if (empty($user_arr['vip_time'])){
                                $date = time();
                            }else{
                                $date = strtotime($user_arr['vip_time']);
                            }
                            $vip_time = date('Y-m-d',strtotime(" +365 day",$date));
                            $vip_arr = Db::table('fa_vip_level')
                                ->where('id',2)
                                ->find();
                            if ($params['money'] >= $vip_arr['renew']){
                                $level = $vip_arr['id'];
                            }else{
                                $this->error(__('收款金额低于续费金额'));
                            }
                        }elseif ($params['cost_way'] == 3){
                            $this->error(__('请先充值成为家庭会员'));
                        }

                    }elseif ($user_arr['level'] == 3){
                        if ($params['cost_way'] == 1){
                            $this->error(__('会员等级已是最高,请续费操作'));
                        }elseif ($params['cost_way'] == 2){
                            if (empty($user_arr['vip_time'])){
                                $date = time();
                            }else{
                                $date = strtotime($user_arr['vip_time']);
                            }
                            $vip_time = date('Y-m-d',strtotime(" +365 day",$date));
                            $vip_arr = Db::table('fa_vip_level')
                                ->where('id',3)
                                ->find();
                            if ($params['money'] >= $vip_arr['renew']){
                                $level = $vip_arr['id'];
                            }else{
                                $this->error(__('收款金额低于会员续费金额'));
                            }
                        }elseif ($params['cost_way'] == 3){
                            $vip_time = $user_arr['vip_time'];
                            $level = 3;
                            $vip_arr = Db::table('fa_vip_level')
                                ->where('id',3)
                                ->find();
                            if ($params['money'] >= $vip_arr['upward']){
                                $counts = floor($params['money']/$vip_arr['upward']);
                            }else{
                                $this->error(__('收款金额低于增加家庭成员费用'));
                            }
                        }
                    }

                    if ($level !== 1){
                        if ($params['cost_way'] != 3){
                            $arr_insert = [];
                            $log = Db::table('fa_vip_relation')
                                ->where('level_id',$level)
                                ->select();

                            foreach ($log as $k=>$v){
                                $deduction_arr = Db::table('fa_deduction')
                                    ->where(['user_id'=>$params['user_id'],'serve_id'=>$v['serve_id']])
                                    ->find();

                                if ($v['status'] == 1){
                                    $countsss = 1;
                                }elseif ($v['status'] == 2){
                                    $countsss = 1;
                                }elseif ($v['status'] == 3){
                                    $countsss = 2;
                                }elseif ($v['status'] == 4){
                                    $countsss = 3;
                                }else{
                                    $countsss = 0;
                                }

                                if (!empty($deduction_arr)){
                                    $insert_s = Db::table('fa_deduction')
                                        ->where('id',$deduction_arr['id'])
                                        ->update([
                                            'count' => $deduction_arr['count']+$countsss,
                                            'update_time' => time(),
                                        ]);
                                }else{

                                    $insert_s = Db::table('fa_deduction')
                                        ->insertGetId([
                                            'user_id' => $params['user_id'],
                                            'serve_id' => $v['serve_id'],
                                            'count' => $countsss,
                                            'create_time' => time(),
                                        ]);
                                }


                                if ($insert_s == false){
                                    Db::rollback();
                                    $this->error('会员权益更新失败');
                                }
                            }


                        }



                    }



                    if ($counts != 0){
                        if ($params['cost_way'] == 3){
                            $counts = $user_arr['count']+$counts;
                        }else{
                            $counts = $counts;
                        }
                    }else{
                        $counts = $user_arr['count'];
                    }

                    $update = Db::table('fa_users')
                        ->where('id',$params['user_id'])
                        ->update([
                            'level' => $level,
                            'count' => $counts,
                            'vip_time' => $vip_time,
                            'update_time' => time(),
                        ]);

                    $updates = Db::table('fa_users')
                        ->where('pid',$params['user_id'])
                        ->update([
                            'level' => $level,
                            'count' => $counts,
                            'vip_time' => $vip_time,
                            'update_time' => time(),
                        ]);


                    $params['vip_time'] = $vip_time;
                    $result = $this->model->allowField(true)->save($params);

                    if (($update !== false) && ($updates !== false) && ($result !== false)){
                        Db::commit();
                    }else{
                        Db::rollback();
                        $this->error('失败');
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }




}
